class instance:
  def __init__(self,fn):
    self.ins = {}
    with open(fn, 'r') as f:
      t = "wrong"
      for line in f:
        if line[0] == '<':
          end = line.find('>',1)
          if end != -1:
            t = line[1:end]
            self.ins[t] = []
        else:
          edge = line.strip().split()
          self.ins[t].append(edge[0])
    self.getRename()


  def getRename(self):
    self.name = {}
    for k in self.ins:
      self.name[k] = {}
      for n in self.ins[k]:
        s = n.find("<")
        e = n.find(">")
        if s!= -1 and e != -1:
          self.name[k][n[:s]] = n[s+1:e]
        else:
          self.name[k][n] = n
    self.lookup = {}
    for k in self.name:
      for i in self.name[k]:
        self.lookup[i] = k
  def getSome(self,key):
    if self.name.__contains__(key):
      return self.name[key]
    else:
      return {}

from graph import graph
import numpy as np
from sklearn.cluster import KMeans,AgglomerativeClustering
import matplotlib.pyplot as plt
from spacetrans import space
from connect import egress,ingress

def main():
  g = graph("../test_flatten.g")
  g.toNum()
  eg = egress(g.nG)
  ig = ingress(g.nG)
  i = instance("../test_flatten.ins")
  keys = ["RAMB36E1","RAMB18E1"]
  # for k in keys:
  #   for kk in i.getSome(k):
  #     print(kk)
  #     if g.lookup.__contains__(kk):
  #       print(g.lookup[kk])
  #     else:
  #       for s in g.name:
  #         if s == kk:
  #           print("find is")
  index = np.array([g.lookup[kk] for k in keys for kk in i.getSome(k) if g.lookup.__contains__(kk) ])
  
  sp = g.fromEMBFile("../test_flatten.emb")

  for i in range(5):
    sp.oneStep(ig)
    sp.oneStep(eg)
    print("*")
  sp.toReal()
  pos = sp.pos[index]
  random_state = 170
  clusters = 5
  c_y = AgglomerativeClustering().fit_predict(pos)
  # c_y = KMeans(n_clusters=clusters, random_state=random_state).fit_predict(pos)
  print(c_y)
  ram = space()
  ram.initByPos(pos)
  ram.down(2)
  note = [[] for i in range(clusters)]
  i = 0
  for (c,n) in zip(c_y,index.tolist()):
    print(c,n,g.name[n],ram.pos[i,0],ram.pos[i,1])
    note[c].append(g.name[n])
    i += 1
  # for n in note:
  #   print(n)
  # print(c_y)
  ram.plot(c_y)
  # plt.scatter(pos[:,0],pos[:,1],s=0.5,c=c_y)
  # plt.show()      
if __name__ == '__main__':
  main()